/*
 *  ufmail, a suite of mail servers
 *  Copyright (C) 2013  Jonathon Keogh
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 *  Jonathon Keogh e-mail: jdkeogh@live.com
 */

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <errno.h>
#include "log.h"
#include "sendf.h"

// Send formatted string
short sendf(int iClient, const char *sBuffer, ...) {
	va_list vArgs;
	char *s;
	int i;

	// How long will the formatted string be?
	va_start(vArgs, sBuffer);
	i = vsnprintf(NULL, 0, sBuffer, vArgs);
	va_end(vArgs);

	// Produce the formatted string
	s = malloc(i+1);
	memset(s, 0, i+1);
	va_start(vArgs, sBuffer);
	i = vsprintf(s, sBuffer, vArgs);
	va_end(vArgs);

	printf("\n%i vsnprintf result\n%i strlen\n", i, strlen(s));

	// Send the formatted string
	i = send(iClient, s, strlen(s), 0);
	if(i < 0) {
		writeToLog(LOG_ERROR, "send() did not succeed, %s", strerror(errno));
	}

	// Clean up
	free(s);

	// Return send return
	return i;
}
